package com.c.authen.modules.sys.service.impl;

import com.c.authen.common.utils.R;
import com.c.authen.common.utils.RedisUtils;
import com.c.authen.modules.sys.service.SysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;


@Service("sysUserTokenService")
@Transactional
public class SysUserTokenServiceImpl implements SysUserTokenService {
	@Autowired
	private RedisUtils redisUtils;
	//12小时后过期  30分钟
	private final static int EXPIRE = 1800;


	@Override
	public R createToken(long userId) {
		//生成一个token
		String token = UUID.randomUUID().toString();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		//SysUserTokenEntity tokenEntity = queryByUserId(userId);
		/*if(tokenEntity == null){
			tokenEntity = new SysUserTokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			redisUtils.set(token, JSONUtil.parse(tokenEntity), EXPIRE);
			//save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			//update(tokenEntity);
			redisUtils.set(token,JSONUtil.parse(tokenEntity), EXPIRE);
		}*/
		redisUtils.set(token, userId, EXPIRE);
		R r = R.ok().put("token", token).put("expire", EXPIRE);

		return r;
	}
}
